var http = require('http') // express带的http模块， 无需安装
var url = require('url') // 把接收到的url转换为url对象， http://baidu.com -> {}， 无需安装
var querystring = require('querystring')

import {REMOTE_ADDRESS} from '../config/index'
// const {REMOTE_ADDRESS} = require('../config')

function NodeAjax() {
  const CONTENT_TYPE = {
    FORM_DATA: 'multipart/form-data; charset=UTF-8',
    FORM: 'application/x-www-form-urlencoded; charset=UTF-8',
    JSON: 'application/json; charset=UTF-8'
  }
  // or NodeAjax.prototype.post = function(){}
  this.post = function (path, data, token, callback, contentType = 'FORM') {
    console.log('REMOTE_ADDRESS:', REMOTE_ADDRESS)
    var urlObj = url.parse(REMOTE_ADDRESS + path)
    var contents
    var headers = { 'content-type': CONTENT_TYPE[contentType] }
    if (contentType === 'JSON') {
      contents = JSON.stringify(data)
    } else {
      contents = querystring.stringify(data)
      Object.assign(headers, {'Content-Length': contents.length, Authorization: token})
    }
    var option = {
      method: 'POST',
      hostname: urlObj.hostname,
      port: urlObj.port,
      path: urlObj.path,
      headers: headers
    }

    var httpCallback = function (response) {
      var body = ''
      response.on('data', function (data) {
        body += data
      })
      response.on('end', function () {
        callback(body)
      })
    }
    var res = http.request(option, httpCallback)
    res.write(contents) // 发送内容
    res.end()
  }

  this.get = function (path, callback) {
    var urlObj = url.parse(REMOTE_ADDRESS + path)
    var option = {
      method: 'GET',
      hostname: urlObj.hostname,
      port: urlObj.port,
      path: urlObj.path,
      headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', Authorization: token }
    }
    var httpCallback = function (response) {
      var body = ''
      response.on('data', function (data) {
        body += data
      })
      response.on('end', function () {
        callback(body)
      })
    }
    var req = http.request(option, httpCallback)

    req.end()
  }
}

export default new NodeAjax()
